<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/08/25
 * Time: 15:24
 * @link http://www.lmterp.cn
 */

namespace app\common\model;

use think\model\relation\BelongsTo;

class ChannelSender extends BaseModel
{
    protected $pk = 'sender_id';

    protected $autoWriteTimestamp = 'datetime';

    protected $insert = ['create_by', 'update_by'];

    protected $update = ['update_by'];

    /**
     * 关联账号
     * @return BelongsTo
     * @date 2020/08/26
     * @author longli
     */
    public function account()
    {
        return $this->belongsTo(Account::class);
    }

    /**
     * 获取默认发货地址
     * @return ChannelSender
     * @date 2020/12/13
     * @author longli
     */
    public static function getDefault()
    {
        return static::where(['is_default' => ChannelSender::IS_YES, "status" => self::IS_YES])->find();
    }

    /**
     * 获取账号指定的发货地址
     * @param int $accountId 账号id
     * @return ChannelSender
     * @date 2020/12/13
     * @author longli
     */
    public static function getByAccount($accountId)
    {
        return static::where(['account_id' => $accountId, "status" => self::IS_YES])->find();
    }

    /**
     * 设置默认发票
     * @param int|self $sender 发货人id，发货人
     * @param bool $force 强制设置
     * @return bool
     * @date 2021/01/15
     * @author longli
     */
    public static function setDefault($sender, $force = false)
    {
        $sender = self::getObj($sender);
        if(empty($sender)) return false;
        if(!$force && $sender->is_default == self::IS_YES) return true;
        static::where("sender_id", ">", 0)
            ->update(['is_default' => self::IS_NO]);
        static::where("sender_id", $sender->sender_id)->update(['is_default' => self::IS_YES]);
        return true;
    }

    /**
     * 获取所有发件人
     * @return static[]
     * @date 2021/01/15
     * @author longli
     */
    public static function getAll()
    {
        return static::where([
            'status' => static::IS_YES
        ])->order("is_default desc, sender_id desc")
        ->select();
    }
}
